<script setup lang="ts">
import { computed, onMounted, onUnmounted, watch, ref} from 'vue';
import {  useDialog,  useNotification} from "naive-ui";
import { resultCodeNotify, resultCustom } from '@/utils/rest/notifyHint'
import { useUserStore} from "@/store";
import { useRouter } from 'vue-router';
import { userLogoutAPI, isInternalIPAddress,
  updateUser2FAMethod,
  userDeviceAPI, isResultLogin, getResultImgUrl, userAPIKEYAPI} from '@/api';
import {getPageData} from "@/api/entity/ResultParam";
import { Selector } from '@/components/common'
import { getCastCurrentDate } from '@/utils/time/timeUtils'
import {userDeviceListModel, userApiKeyFilterModel} from "@/api/entity/RequestParam";
import { BindAccount, AccountDetail, ApiNameDetail} from "@/views/dashboard/profile/components"
import { copyEvent} from "@/utils/rest/browserVersion";


const userStore = useUserStore();            // 缓存
const router = useRouter();                  // 路由跳转
const hint = useNotification();              // 提示
const dialog = useDialog();                  // 对话框
const title = "退出登录";
const userBasic = ref<User.userSetting>({});
const userAccount = ref<User.basicInfo>({})
const userDeviceList = ref<getPageData>({pageList: [], currentPage: 0, pageCount: 0})
const userApiList = ref<getPageData>({pageList: [], currentPage: 0, pageCount: 0})
const selectDevice = ref('所有')
const deviceList = ref([
    {value: '所有', text: "所有"},
    {value: 'Windows', text: "Windows"},
    {value: 'Android', text: '安卓'},
    {value: 'iOS', text: '苹果'},
    {value: 'Unknown' , text: '未知'}])

const requestUserDeviceParam = ref<userDeviceListModel>(
    {deviceModel: '',  count: 4, page: 0})
const requestUserAPIParam = ref<userApiKeyFilterModel>({count: 3, page: 0})
const isLoadDevice = ref<boolean>(false);       //  是否初始化设备
const isLoadApi = ref<boolean>(false);       //  是否初始化设备

/**
 *  初始化
 */
onMounted(() => {
  initUserBasicInfo(); // 初始化用户数据
  getUserDeviceList(); // 设备数据
  getUserKeyList();
})



/**
 * 初始化 用户基础信息
 */
function initUserBasicInfo() {
  const user:User.saveUserInfo = userStore.getAppointUserInfo()
  userBasic.value = user.userSetting
  userAccount.value = user.userBasic
}


/**
 * 识别设别ip
 */
// async function discernIP(ip: string) {
//   if (isInternalIPAddress(ip)) {
//     return "未知";
//   }
//   try {
//     const result = await getIPAddressAPI(ip);
//     return result.country + "-" + result.regionName + "-" + result.city; // 假设 API 返回的对象有一个 data 属性包含所需信息
//   } catch (error) {
//     return "未知"; // 或者返回其他合适的默认值
//   }
// }
// async function fetchDeviceIPInfo() {
//   for (const device of userDeviceList.value.pageList) {
//     device.ipInfo = await discernIP(device.ipAddress); // 将结果存储在设备的 ipInfo 属性中
//   }
// }
// watch(userDeviceList, fetchDeviceIPInfo, { deep: true });


/**
 * 退出登录
 */
function handleUserLogout() {
  dialog.info({
    title: '确认退出登录吗?',
    positiveText: '退出登录',
    onPositiveClick: () =>{
      userLogoutAPI().then(res => {
        resultCodeNotify(hint, title, res);
        if (res.code === 200) {
          userStore.removeUserInfo();
          router.push('/login');
        }
      }).catch(error => {
        resultCodeNotify(hint, title, error);
      })
    }
  })
}

/**
 * 获取用户设备数
 */
function getUserDeviceList() {
  if (!isLoadDevice.value) {
    isLoadDevice.value = true
    userDeviceAPI(requestUserDeviceParam.value).then(res => {
      isResultLogin(res.code, router)
      if (res.code === 200) {
        const resultData:getPageData = res.data
        if (Array.isArray(userDeviceList.value.pageList) && Array.isArray(resultData.pageList)) {
          userDeviceList.value.pageList = [...userDeviceList.value.pageList, ...resultData.pageList];
        }
        userDeviceList.value.pageCount = resultData.pageCount;
        userDeviceList.value.currentPage = resultData.currentPage;
        isLoadDevice.value = false;
      }
    }).catch(error => {
      isLoadDevice.value = false;
    })
  }
}

/**
 *  用户api key
 */
function getUserKeyList() {
  if (!isLoadApi.value) {
    isLoadApi.value = true
    userAPIKEYAPI(requestUserAPIParam.value).then(res => {
      isResultLogin(res.code, router)
      if (res.code === 200) {
        const resultData:getPageData = res.data
        if (Array.isArray(userApiList.value.pageList) && Array.isArray(resultData.pageList)) {
          userApiList.value.pageList = [...userApiList.value.pageList, ...resultData.pageList];
          userApiList.value.pageCount = resultData.pageCount;
          userApiList.value.currentPage = resultData.currentPage;
          isLoadApi.value = false;
        }
      }
    }).catch(error => {
      isLoadDevice.value = false;
    })
  }
}

/**
 * 处理选择事件
 */
const handleSelectChange = (newValue: string) => {
  const initUserDevice = {pageList: [], currentPage: 0, pageCount: 0};
  userDeviceList.value = initUserDevice
  const  initRequestParm = {deviceModel: '',  count: 4, page: 0};
  if (newValue !== '所有') {
    initRequestParm.deviceModel = newValue
  }
  requestUserDeviceParam.value = initRequestParm;
  getUserDeviceList()
  // 处理新选中的设备值的逻辑
};

/**
 * 滚动数据
 * @param event
 */
function loadMoreUserDeviceData(event) {
  const scrollTop = event.target.scrollTop + 1.6;
  //window.alert(scrollTop + event.target.clientHeight + "  " + event.target.scrollHeight)
  // 你可以在这里添加自己的逻辑，比如无限滚动加载更多数据等
  if (scrollTop + event.target.clientHeight >= event.target.scrollHeight) {
    // 滚动到底部了，可以加载更多数据
    requestUserDeviceParam.value.page = userDeviceList.value.currentPage + 1
    if (requestUserDeviceParam.value.page < userDeviceList.value.pageCount) {
      getUserDeviceList()
    }
  }
}

function loadMoreUserApiData(event) {
  const scrollTop = event.target.scrollTop + 1.6;
  //window.alert(scrollTop + event.target.clientHeight + "  " + event.target.scrollHeight)
  // 你可以在这里添加自己的逻辑，比如无限滚动加载更多数据等
  if (scrollTop + event.target.clientHeight >= event.target.scrollHeight) {
    // 滚动到底部了，可以加载更多数据
    requestUserAPIParam.value.page = userApiList.value.currentPage + 1
    if (requestUserAPIParam.value.page < userApiList.value.pageCount) {
      getUserKeyList()
    }
  }
}


const bind_account_dialog = ref<boolean>(false)
const account_detail = ref<boolean>(false)
const api_name_dialog = ref<boolean>(false)
const dialog_data_list = [
  {different: 1, title: "邮箱账号" },
  {different: 3, title: "手机号码"},
  {different: 2, title: "二向验证"}

]
const dialog_data = ref({different: 0, title: ''})

/**
 * 监听dialog 组件关闭事件
 */
function handleDialogClosed() {
  bind_account_dialog.value = false;
}
function accountDiglogClosed() {
  account_detail.value = false;
}
function apiNameDialogClosed() {
  api_name_dialog.value = false;
}

/**
 * 打开对话框
 * @param different
 * @param suffix
 */
function openDialog(different: number, suffix: string) {
  const getDialog = dialog_data_list[different].title
  dialog_data.value = {different: dialog_data_list[different].different, title: suffix + getDialog}
  bind_account_dialog.value = true
}
function openAccountDialog() {
  account_detail.value = true
}

function openApiNameDialog() {
  api_name_dialog.value = true
}

/**
 * 复制事件
 */
function copyApiKey(copyText: string) {
  copyEvent(copyText, hint)
}
</script>

<template>
    <div>
      <BindAccount v-if="bind_account_dialog"
                   :different="dialog_data.different"
                   :title="dialog_data.title"
                   @dialog-closed="handleDialogClosed"></BindAccount>

      <AccountDetail v-if="account_detail" @account_dialog-closed="accountDiglogClosed"></AccountDetail>

      <ApiNameDetail v-if="api_name_dialog" @api_dialog-closed="apiNameDialogClosed"></ApiNameDetail>
    <div class="row w-90 mx-auto pt-10 pb-10">
      <!-- Column -->
      <div class="col-lg-5 position-relative mb-10">
        <div class="user-edit" @click="openAccountDialog">
          <img src="https://cdn.iextend.top/pay/svg/editor.svg"/>
        </div>
        <div class="user-img col-6 mx-auto" @click="openAccountDialog">
          <img
              class="img-circle mx-auto"
              :src="userBasic.iconUrl || 'https://th.bing.com/th/id/R.e7374c116733a48d6bd55f77c878193d?rik=3xO%2fFHlI7DICmw&riu=http%3a%2f%2fimg.keaiming.com%2fuploads%2fallimg%2f2020052714%2fm03l2s3ztpj.jpeg&ehk=rjs22BrJwcnwO6FNaiHU2O6zwffYuGpHXz133mQnbLY%3d&risl=&pid=ImgRaw&r=0'"
              width="150"/>
          <h4 class="fw-bold text-center">{{userBasic.name || '1'}}</h4>
          <p class="text-overflow w-100 text-center">{{userBasic.motto || '你人很懒耶, 要不要说些什么呀!'}}</p>
        </div>

        <div class="col-10 mx-auto">
          <div class="card-info w-100 mb-3 d-flex pt-3">
            <p>最近登录地址:</p>
            <p class="text-right-not">广东省深圳市</p>
          </div>
        </div>

        <div class="col-10 mx-auto">
          <div class="card-info w-100 mb-3 d-flex pt-3">
            <p>最近登录时间:</p>
            <p class="text-right-not">{{userBasic.lastOneTime}}</p>
          </div>
        </div>

        <div class="col-10 mx-auto">
          <div class="card-info w-100 mb-3 d-flex pt-3">
            <p>API调用次数:</p>
            <p class="text-right-not">240 次</p>
          </div>
        </div>

        <div class="col-10 mx-auto"
             @click="openDialog(0, userAccount.email === '' ? '绑定' : '换绑')">
          <div class="card-info w-100 mb-3 d-flex pt-3">
            <p>邮箱:</p>
            <p class="text-right-all">{{userAccount.email}}</p>
            <p class="icon-more text-primary">{{userAccount.email === '' ? '绑定' : '换绑'}}</p>
          </div>
        </div>

        <div class="col-10 mx-auto"
             @click="openDialog(1, userAccount.phone === undefined ? '绑定' : '换绑')">
          <div class="card-info w-100 mb-3 d-flex pt-3">
            <p>手机号码:</p>
            <p class="text-right-all">{{userAccount.phone}}</p>
            <p class="icon-more text-primary">{{userAccount.phone === undefined ? '绑定' : '换绑'}}</p>
          </div>
        </div>

        <div class="col-10 mx-auto mb-3"
             @click="openDialog(2, userAccount.twoSecret === undefined ? '绑定' : '换绑')">
          <div class="card-info w-100 mb-3 d-flex pt-3">
            <p>二向验证码:</p>
            <p class="text-right-all">{{userAccount.twoSecret}}</p>
            <p class="icon-more text-primary">{{userAccount.twoSecret === undefined ? '绑定' : '换绑'}}</p>
          </div>
        </div>

        <div class="col-10 mx-auto">
          <div class="card-info w-100 mb-3 d-flex pt-3">
            <p>QQ登录:</p>
            <p class="text-right-all"></p>
            <p class="icon-more text-primary">待开发</p>
          </div>
        </div>

        <div class="col-10 mx-auto">
          <div class="card-info w-100 mb-3 d-flex pt-3">
            <p>微信登录:</p>
            <p class="text-right-all">176***5942</p>
            <p class="icon-more text-primary">待开发</p>
          </div>
        </div>



        <div class="col-10 mx-auto">
          <NButton class="w-100" type="info"  @click="handleUserLogout">退出登录</NButton>
        </div>

      </div>

      <div class="col-lg-7 mx-auto ">
        <div class="my-wallet mb-5">
          <div class="w-85 d-flex mb-3">
            <p class="col-9 fs-4 text-primary">
              API KEY
            </p>
            <p class="col-1 ml-20 pt-2" @click="openApiNameDialog">
              <img class="img-create-wallet" src="https://cdn.iextend.top/pay/svg/plus.svg"/>
            </p>
          </div>

          <div class="datatable-table-api w-98 ml-5" @scroll="loadMoreUserApiData">
            <table class="table text-sm" >
              <thead>
              <tr>
                <th>名称</th>
                <th>api key</th>
                <th>调用次数</th>
                <th>创建日期</th>
                <th>操作</th>
              </tr>
              </thead>
              <tbody>
                <tr class="tr-lable" v-for="(api, index) in userApiList.pageList" :key="index">
                  <td class="td_lable">{{ api.name }}</td>
                  <td class="td_lable">
                    <p class="text-overflow ">{{ api.apiKey }}</p>
                  </td>
                  <td class="td_lable">{{ api.paymentCount }}</td>
                  <td class="td_lable">{{getCastCurrentDate(api.createTime)}}</td>
                  <td class="td_lable">
                      <div>
                        <NButton @click="copyApiKey(api.apiKey)">复制</NButton>
                      </div>
                      <div class="mt-2">
                        <NButton type="error">删除</NButton>
                      </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>


        <div class="mb-3 col-10 ml-6 d-flex">
          <div class="col-9 fs-4 text-primary">登录设备</div>
          <Selector class="col-4  mx-auto mt-1"
                    :label="''"
                    @change="handleSelectChange"
                    :options="deviceList"
                    :value="selectDevice" />
        </div>
        <div class="datatable-table w-98 ml-5" @scroll="loadMoreUserDeviceData">
          <table class="table text-sm" >
            <thead>
            <tr>
              <th>设备型号</th>
              <th>最近地址</th>
              <th>登录时间</th>
              <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr class="tr-lable" v-for="(device, index) in userDeviceList.pageList" :key="index">
              <td class="td_lable">
                <div class="d-flex">
                  <img class="device-img" :src="getResultImgUrl(device.deviceIcon)"/>
                  <p>{{ device.deviceModel }}</p>
                </div>
                {{ device.appVersion }}
              </td>

              <td class="td_lable">{{ device.ipAddress }}</td>
              <td class="td_lable">{{getCastCurrentDate(device.lastOneTime)}}</td>
              <td class="td_lable">
                <div class="mt-2">
                  <NButton type="error">删除</NButton>
                </div>
              </td>
            </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    </div>
</template>

<style scoped>
.datatable-table {
  height: 22rem;
  overflow-y: auto;
  display: block;
  box-shadow: 0 0 1.5px #2F80ED;
  border-radius: 5px;
}

.datatable-table-api {
  height: 17rem;
  overflow-y: auto;
  display: block;
  box-shadow: 0 0 1.5px #2F80ED;
  border-radius: 5px;
}


.table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed; /* 确保列宽一致 */
}

thead {
  width: 100%;
  height: 3.5rem;
  line-height: 3.5rem;
}

thead th {
  position: sticky; /* 启用粘性定位 */
  top: 0; /* 固定在顶部 */
  background-color: #fff; /* 确保thead在滚动时背景色不变 */
  z-index: 1; /* 确保thead在tbody上方 */
}
thead th::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 0.1px;
  background-color: #2F80ED; /* 或者你想要的边框颜色 */
}

/* 滚动条整体样式 */
.datatable-table::-webkit-scrollbar {
  width: 10px; /* 滚动条的宽度 */
}

/* 滚动条滑块样式 */
.datatable-table::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.3); /* 滑块颜色 */
  border-radius: 10px; /* 滑块边角 */
}

/* 滚动条滑块悬停样式 */
.datatable-table::-webkit-scrollbar-thumb:hover {
  cursor: pointer;
  background-color: rgba(0, 0, 0, 0.5); /* 滑块悬停时的颜色 */
  border-radius: 10px; /* 滑块边角 */
}

/* 滚动条轨道样式 */
.datatable-table::-webkit-scrollbar-track {
  background-color: #2F80ED; /* 轨道颜色 */
  border-radius: 10px; /* 轨道边角 */
}


/* 滚动条整体样式 */
.datatable-table-api::-webkit-scrollbar {
  width: 10px; /* 滚动条的宽度 */
}

/* 滚动条滑块样式 */
.datatable-table-api::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.3); /* 滑块颜色 */
  border-radius: 10px; /* 滑块边角 */
}

/* 滚动条滑块悬停样式 */
.datatable-table-api::-webkit-scrollbar-thumb:hover {
  cursor: pointer;
  background-color: rgba(0, 0, 0, 0.5); /* 滑块悬停时的颜色 */
  border-radius: 10px; /* 滑块边角 */
}

/* 滚动条轨道样式 */
.datatable-table-api::-webkit-scrollbar-track {
  background-color: #2F80ED; /* 轨道颜色 */
  border-radius: 10px; /* 轨道边角 */
}




.device-img{
  margin-top: -0.6rem;
  margin-right: 1rem;
  width: 2rem;
  height: 2rem;
}
.td_lable {
  height: 7rem;
  vertical-align: middle;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.scrollable-tbody {
  display: block;
  max-height: 300px;
  overflow-y: auto;
  position: relative;
}

.tr-lable:hover {
  color: red;
  cursor: pointer;
  transform: scale(0.99);
}

.user-edit:hover{
  transform: scale(1.1);
}
.user-edit {
  position: absolute;
  right: 10%;
  color: #2F80ED;
}

.text-overflow {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.img-create-wallet{
  width: 35px;
  height: 35px;
}
.img-create-wallet:hover {
  cursor: pointer;
  transform: scale(1.1);
}
.img-circle {
  border-radius: 100%;
}
.user-img:hover{
  color: red;
  transform: scale(0.99);
}
.icon-more {
  position: absolute;
  right: 0px;
}

.card-info:hover {
  color: red;
  transform: scale(0.99);
  cursor: pointer;
}

.card:hover {
  color: red;
  transform: scale(0.99);
  cursor: pointer;
}
.text-right-all {
  position: absolute;
  right: 15%;
}
.text-right-not{
  position: absolute;
  right: 2%;
}

.card-info {
  position: relative;
  height: 3rem;
  border-bottom: 1px solid #2F80ED;
}

</style>
